/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * VentanaVentas.java
 *
 * Created on 25/07/2011, 00:01:02
 */

package ventanas;

import conexiones.AdministradorDeConexiones;
import dao.ArticulosDao;
import dao.VentasDao;
import java.sql.Connection;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.Iterator;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JOptionPane;
import javax.swing.table.DefaultTableModel;
import modelo.Articulo;
import modelo.Usuario;
import modelo.Venta;

/**
 *
 * @author Cristian Perez
 */
public class VentanaVentas extends javax.swing.JDialog {

    private DefaultTableModel modeloVentas = new DefaultTableModel();
    private ArrayList<Object> listaVentas;
    public static Articulo articuloRecibidoXbusqueda;


    //La variable hoy se utiliza para tener la fecha y hora del momento en que se realiza la venta
    Date hoy;

    /**
     *El string codBarra es Utilizado para para trabajar con el codigo de barras de la venta en todos metodos
     */
    String codBarra = null;

    /** Creates new form VentanaVentas */
    public VentanaVentas(java.awt.Frame parent, boolean modal) {

        super(parent, modal);
        initComponents();

        hoy = new Date();

        modeloVentas = (DefaultTableModel) tablaVentas.getModel();
        tablaVentas.setModel(modeloVentas);

        estructurarTabla();
        lblHora.setText(devolverHoraActual());
        lblFecha1.setText(devolverFechaActual());
        lblUsr.setText(MenuPrincipal.getUsuarioLogueado().getNombreUsuario().trim());
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jPanel1 = new javax.swing.JPanel();
        jPanel2 = new javax.swing.JPanel();
        jLabel9 = new javax.swing.JLabel();
        lblTotal = new javax.swing.JLabel();
        btnEliminar = new javax.swing.JButton();
        btnConfirmar = new javax.swing.JButton();
        jPanel3 = new javax.swing.JPanel();
        lblFecha = new javax.swing.JLabel();
        lblApertura = new javax.swing.JLabel();
        lblFecha1 = new javax.swing.JLabel();
        lblHora = new javax.swing.JLabel();
        lblUsuario = new javax.swing.JLabel();
        lblUsr = new javax.swing.JLabel();
        jPanel4 = new javax.swing.JPanel();
        lblCantidad = new javax.swing.JLabel();
        txtCantidad = new javax.swing.JTextField();
        lblCodigo = new javax.swing.JLabel();
        txtCodigo = new javax.swing.JTextField();
        jLabel1 = new javax.swing.JLabel();
        jPanel6 = new javax.swing.JPanel();
        jScrollPane1 = new javax.swing.JScrollPane();
        tablaVentas = new javax.swing.JTable();
        jPanel5 = new javax.swing.JPanel();
        btnSalir = new javax.swing.JButton();
        jSeparator1 = new javax.swing.JSeparator();
        jSeparator2 = new javax.swing.JSeparator();

        setDefaultCloseOperation(javax.swing.WindowConstants.DO_NOTHING_ON_CLOSE);
        setTitle("FACTURACION");
        addWindowListener(new java.awt.event.WindowAdapter() {
            public void windowClosing(java.awt.event.WindowEvent evt) {
                formWindowClosing(evt);
            }
        });

        jPanel1.setPreferredSize(new java.awt.Dimension(900, 607));

        jPanel2.setBorder(new javax.swing.border.SoftBevelBorder(javax.swing.border.BevelBorder.RAISED));
        jPanel2.setPreferredSize(new java.awt.Dimension(825, 70));

        jLabel9.setFont(new java.awt.Font("Times New Roman", 1, 14)); // NOI18N
        jLabel9.setText("TOTAL --->");

        lblTotal.setFont(new java.awt.Font("Tahoma", 1, 36)); // NOI18N
        lblTotal.setForeground(new java.awt.Color(153, 0, 255));
        lblTotal.setText("0.00");

        btnEliminar.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N
        btnEliminar.setText("Eliminar Item");
        btnEliminar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnEliminarActionPerformed(evt);
            }
        });

        btnConfirmar.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N
        btnConfirmar.setText("Confirmar Venta");
        btnConfirmar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnConfirmarActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2);
        jPanel2.setLayout(jPanel2Layout);
        jPanel2Layout.setHorizontalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel2Layout.createSequentialGroup()
                .addGap(55, 55, 55)
                .addComponent(btnEliminar, javax.swing.GroupLayout.PREFERRED_SIZE, 123, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(107, 107, 107)
                .addComponent(btnConfirmar)
                .addGap(140, 140, 140)
                .addComponent(jLabel9)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 40, Short.MAX_VALUE)
                .addComponent(lblTotal, javax.swing.GroupLayout.PREFERRED_SIZE, 169, javax.swing.GroupLayout.PREFERRED_SIZE))
        );
        jPanel2Layout.setVerticalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel2Layout.createSequentialGroup()
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addGroup(javax.swing.GroupLayout.Alignment.LEADING, jPanel2Layout.createSequentialGroup()
                        .addGap(20, 20, 20)
                        .addComponent(lblTotal, 0, 0, Short.MAX_VALUE))
                    .addGroup(javax.swing.GroupLayout.Alignment.LEADING, jPanel2Layout.createSequentialGroup()
                        .addGap(19, 19, 19)
                        .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(btnEliminar, javax.swing.GroupLayout.PREFERRED_SIZE, 33, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(btnConfirmar, javax.swing.GroupLayout.PREFERRED_SIZE, 33, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(jLabel9, javax.swing.GroupLayout.PREFERRED_SIZE, 27, javax.swing.GroupLayout.PREFERRED_SIZE))))
                .addContainerGap(17, Short.MAX_VALUE))
        );

        lblFecha.setFont(new java.awt.Font("Tahoma", 1, 14));
        lblFecha.setText("Fecha:");

        lblApertura.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N
        lblApertura.setText("Hora Apertura: ");

        lblFecha1.setBackground(new java.awt.Color(255, 255, 255));
        lblFecha1.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N
        lblFecha1.setForeground(new java.awt.Color(51, 51, 255));

        lblHora.setBackground(new java.awt.Color(255, 255, 255));
        lblHora.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N
        lblHora.setForeground(new java.awt.Color(51, 51, 255));

        lblUsuario.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N
        lblUsuario.setText("Usuario: ");

        lblUsr.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N
        lblUsr.setForeground(new java.awt.Color(51, 51, 255));

        javax.swing.GroupLayout jPanel3Layout = new javax.swing.GroupLayout(jPanel3);
        jPanel3.setLayout(jPanel3Layout);
        jPanel3Layout.setHorizontalGroup(
            jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel3Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(lblFecha, javax.swing.GroupLayout.PREFERRED_SIZE, 58, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(lblFecha1, javax.swing.GroupLayout.PREFERRED_SIZE, 106, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(45, 45, 45)
                .addComponent(lblApertura)
                .addGap(18, 18, 18)
                .addComponent(lblHora, javax.swing.GroupLayout.PREFERRED_SIZE, 110, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(43, 43, 43)
                .addComponent(lblUsuario)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(lblUsr, javax.swing.GroupLayout.DEFAULT_SIZE, 201, Short.MAX_VALUE)
                .addGap(52, 52, 52))
        );
        jPanel3Layout.setVerticalGroup(
            jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel3Layout.createSequentialGroup()
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(lblUsr, javax.swing.GroupLayout.PREFERRED_SIZE, 17, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(lblUsuario)
                    .addComponent(lblApertura)
                    .addComponent(lblHora, javax.swing.GroupLayout.PREFERRED_SIZE, 15, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(lblFecha1, javax.swing.GroupLayout.PREFERRED_SIZE, 15, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(lblFecha))
                .addGap(22, 22, 22))
        );

        jPanel4.setBorder(new javax.swing.border.SoftBevelBorder(javax.swing.border.BevelBorder.RAISED));

        lblCantidad.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N
        lblCantidad.setText("Cantidad: ");

        txtCantidad.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N
        txtCantidad.setText("1");
        txtCantidad.setEnabled(false);
        txtCantidad.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyPressed(java.awt.event.KeyEvent evt) {
                txtCantidadKeyPressed(evt);
            }
        });

        lblCodigo.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N
        lblCodigo.setText("Codigo: ");

        txtCodigo.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N
        txtCodigo.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyPressed(java.awt.event.KeyEvent evt) {
                txtCodigoKeyPressed(evt);
            }
        });

        jLabel1.setForeground(new java.awt.Color(204, 0, 0));
        jLabel1.setText("[F2] Habilita ingreso manual de cantidad");

        javax.swing.GroupLayout jPanel4Layout = new javax.swing.GroupLayout(jPanel4);
        jPanel4.setLayout(jPanel4Layout);
        jPanel4Layout.setHorizontalGroup(
            jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel4Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
                    .addComponent(jLabel1, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addGroup(javax.swing.GroupLayout.Alignment.LEADING, jPanel4Layout.createSequentialGroup()
                        .addComponent(lblCantidad, javax.swing.GroupLayout.PREFERRED_SIZE, 72, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(txtCantidad, javax.swing.GroupLayout.PREFERRED_SIZE, 48, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(18, 18, 18)
                        .addComponent(lblCodigo, javax.swing.GroupLayout.PREFERRED_SIZE, 64, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(txtCodigo, javax.swing.GroupLayout.PREFERRED_SIZE, 302, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap())
        );
        jPanel4Layout.setVerticalGroup(
            jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel4Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(lblCantidad)
                    .addComponent(txtCantidad, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(lblCodigo)
                    .addComponent(txtCodigo, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jLabel1)
                .addContainerGap(32, Short.MAX_VALUE))
        );

        tablaVentas.setFont(new java.awt.Font("MS Reference Sans Serif", 1, 14)); // NOI18N
        tablaVentas.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {

            },
            new String [] {
                "CANTIDAD", "DESCRIPCION", "PRECIO U.", "TOTAL"
            }
        ) {
            boolean[] canEdit = new boolean [] {
                false, false, false, false
            };

            public boolean isCellEditable(int rowIndex, int columnIndex) {
                return canEdit [columnIndex];
            }
        });
        jScrollPane1.setViewportView(tablaVentas);
        tablaVentas.getColumnModel().getColumn(0).setResizable(false);
        tablaVentas.getColumnModel().getColumn(1).setResizable(false);
        tablaVentas.getColumnModel().getColumn(2).setResizable(false);
        tablaVentas.getColumnModel().getColumn(3).setResizable(false);

        javax.swing.GroupLayout jPanel6Layout = new javax.swing.GroupLayout(jPanel6);
        jPanel6.setLayout(jPanel6Layout);
        jPanel6Layout.setHorizontalGroup(
            jPanel6Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 838, Short.MAX_VALUE)
        );
        jPanel6Layout.setVerticalGroup(
            jPanel6Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 315, Short.MAX_VALUE)
        );

        btnSalir.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N
        btnSalir.setText("Salir");
        btnSalir.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnSalirActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout jPanel5Layout = new javax.swing.GroupLayout(jPanel5);
        jPanel5.setLayout(jPanel5Layout);
        jPanel5Layout.setHorizontalGroup(
            jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel5Layout.createSequentialGroup()
                .addContainerGap(705, Short.MAX_VALUE)
                .addComponent(btnSalir, javax.swing.GroupLayout.PREFERRED_SIZE, 123, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap())
        );
        jPanel5Layout.setVerticalGroup(
            jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel5Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(btnSalir, javax.swing.GroupLayout.PREFERRED_SIZE, 33, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(4, Short.MAX_VALUE))
        );

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jSeparator1, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 848, Short.MAX_VALUE)
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addContainerGap()
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jSeparator2, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 838, Short.MAX_VALUE)
                            .addComponent(jPanel3, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(jPanel6, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                            .addComponent(jPanel5, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                            .addComponent(jPanel2, javax.swing.GroupLayout.DEFAULT_SIZE, 838, Short.MAX_VALUE)
                            .addComponent(jPanel4, javax.swing.GroupLayout.DEFAULT_SIZE, 838, Short.MAX_VALUE))))
                .addContainerGap())
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jPanel3, javax.swing.GroupLayout.PREFERRED_SIZE, 38, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jSeparator1, javax.swing.GroupLayout.PREFERRED_SIZE, 10, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(2, 2, 2)
                .addComponent(jPanel4, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jPanel6, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jPanel2, javax.swing.GroupLayout.PREFERRED_SIZE, 75, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(5, 5, 5)
                .addComponent(jSeparator2, javax.swing.GroupLayout.PREFERRED_SIZE, 10, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(3, 3, 3)
                .addComponent(jPanel5, javax.swing.GroupLayout.PREFERRED_SIZE, 48, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap())
        );

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, 858, Short.MAX_VALUE)
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, 636, Short.MAX_VALUE)
                .addContainerGap())
        );

        java.awt.Dimension screenSize = java.awt.Toolkit.getDefaultToolkit().getScreenSize();
        setBounds((screenSize.width-894)/2, (screenSize.height-685)/2, 894, 685);
    }// </editor-fold>//GEN-END:initComponents

    private void txtCodigoKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_txtCodigoKeyPressed
        // TODO add your handling code here:

       /**
         * Si presionamos la tecla F2 se habilita el campo de texto cantidad
         */
        if (evt.getKeyCode() == 113) {
            txtCantidad.setEnabled(true);
            txtCantidad.setText("");
            txtCantidad.requestFocus();
        }
        /**
         * Si presonamos la tecla enter se agrega el artiulo perteneciente al codigo ingresado en la venta
         */

        if (evt.getKeyCode() == 10) {
                /**
                 * 
                 */
                Connection conn = null;
                long codigo;
                codBarra = txtCodigo.getText().trim();
                try {
                    conn = AdministradorDeConexiones.obtenerConexion();
                    
                    //Se parsea el string a un entero
                    //codigo = Long.parseLong(txtCodigo.getText().trim());
                    if (codBarra.charAt(0) == '2') {
                        String codAcargar = codBarra.substring(0, 6);
                        codigo = Long.parseLong(codAcargar);
                    }
                    else codigo = Long.parseLong(codBarra);

                    //Paso el parseo, por lo tanto se ingreso un numero entero

                    float total;
                    //Si el codigo de articulo existe en la base se agrega a la venta
                    if (ArticulosDao.getInstance().verificarExistenciaArt(conn, codigo)) {
                            Articulo art = ArticulosDao.getInstance().getArticuloXcodigo(conn, codigo);
                            int cantidad = Integer.parseInt(txtCantidad.getText().trim());
                            Usuario usr = MenuPrincipal.getUsuarioLogueado();
                            String fecha = lblFecha1.getText().trim();
                            String hora = lblHora.getText().trim();
                           
                            if (codBarra.charAt(0) == '2') {
                                total = (obtenerPrecioDeCodigoDeBarra(codBarra) * cantidad);
                            }
                            else {
                                total = (art.getPreVenta() * cantidad);
                            }
                            
                            Venta unaVenta = new Venta(usr, art, cantidad, fecha, hora, total);
                            VentasDao.getInstance().agregar(conn, unaVenta);
                            txtCodigo.setText("");
                            txtCantidad.setText("1");
                            cargarVenta();
                            totalizar();
                    }
                    else {
                        JOptionPane.showMessageDialog(this, "No existe ningun articulo con el codigo ingresado!!!", "Error", JOptionPane.INFORMATION_MESSAGE);
                        txtCodigo.setText("");
                        txtCodigo.requestFocus();
                    }
                }
                catch(NumberFormatException nfe) {
                    try {
                        //Ingreso por el if de descripcion
                        if (ArticulosDao.getInstance().existeFiltroArt(conn, txtCodigo.getText().trim())) {
                            VentaPorDescripcion ventaDesc = new VentaPorDescripcion(this, true);
                            ventaDesc.buscarDescripcion(txtCodigo.getText().trim());
                            ventaDesc.setVisible(true);
                            if (articuloRecibidoXbusqueda != null) {
                                int cantidad = Integer.parseInt(txtCantidad.getText().trim());
                                Usuario usr = MenuPrincipal.getUsuarioLogueado();
                                String fecha = lblFecha1.getText().trim();
                                String hora = lblHora.getText().trim();
                                float total = (articuloRecibidoXbusqueda.getPreVenta() * cantidad);
                                Venta unaVenta = new Venta(usr, articuloRecibidoXbusqueda, cantidad, fecha, hora, total);
                                VentasDao.getInstance().agregar(conn, unaVenta);
                                txtCantidad.setText("1");
                                cargarVenta();
                                totalizar();
                                articuloRecibidoXbusqueda = null;
                            }
                            txtCodigo.setText("");
                        }
                        else {
                            JOptionPane.showMessageDialog(this, "La descripcion no coincide con ningun articulo...", "Error", JOptionPane.INFORMATION_MESSAGE);
                            txtCodigo.setText("");
                        }
                    }catch(Exception e){e.printStackTrace();}
                }
                catch(Exception e) {
                        e.printStackTrace();
                }
        }
    }//GEN-LAST:event_txtCodigoKeyPressed

    private void txtCantidadKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_txtCantidadKeyPressed
        // TODO add your handling code here:

        /**
         * Si se presiona la tecla escape, el campo cantidad pierde el foco
         */
        if (evt.getKeyCode() == 27) {
            txtCantidad.setEnabled(false);
            txtCantidad.setText("1");
            txtCodigo.setText("");
            txtCodigo.requestFocus();
        }
        if (evt.getKeyCode() == 10) {
            try {
                if (Integer.parseInt(txtCantidad.getText().trim()) > 0 ){
                    txtCantidad.setEnabled(false);
                    txtCodigo.setText("");
                    txtCodigo.requestFocus();
                }
            }catch(NumberFormatException nfe) {
                JOptionPane.showMessageDialog(this, "Debe ingresar una cantidad valida...", "Cantidad", JOptionPane.WARNING_MESSAGE);
                txtCantidad.setText("");
                txtCantidad.requestFocus();
            }
        }
    }//GEN-LAST:event_txtCantidadKeyPressed

    private void formWindowClosing(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_formWindowClosing
        // TODO add your handling code here:
        if (tablaVentas.getRowCount() != 0) {
            int rta = JOptionPane.showConfirmDialog(this,
                                        "Esta seguro de cancelar la venta ?",
                                        "Alerta",
                                        JOptionPane.YES_NO_OPTION);

            // Si no desea borrarlo, entonces no lo borra
            if(rta == JOptionPane.NO_OPTION) {
                txtCodigo.requestFocus();
                return;
            }
        }
        vaciarTablaVentas();
        this.dispose();
    }//GEN-LAST:event_formWindowClosing

    
    private void btnSalirActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnSalirActionPerformed
        // TODO add your handling code here:
        if (tablaVentas.getRowCount() != 0) {
            int rta = JOptionPane.showConfirmDialog(this,
                                        "Esta seguro de cancelar la venta ?",
                                        "Alerta",
                                        JOptionPane.YES_NO_OPTION);

            // Si no desea borrarlo, entonces no lo borra
            if(rta == JOptionPane.NO_OPTION) {
                txtCodigo.requestFocus();
                return;
            }
        }
        vaciarTablaVentas();
        this.dispose();
    }//GEN-LAST:event_btnSalirActionPerformed

    private void btnEliminarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnEliminarActionPerformed
        // TODO add your handling code here:
        Connection conn = null;
        if (tablaVentas.getRowCount() == 0) {
            JOptionPane.showMessageDialog(this, "No existen ventas a eliminar!!!", "Error", JOptionPane.INFORMATION_MESSAGE);
            txtCodigo.requestFocus();
        }
        else if (tablaVentas.getSelectedRowCount() == 0){
            JOptionPane.showMessageDialog(this, "No ha seleccionado ninguna venta para eliminar...", "Error", JOptionPane.INFORMATION_MESSAGE);
            txtCodigo.requestFocus();
        }
        else if (tablaVentas.getSelectedRowCount() < 2 ) {
            int rta = JOptionPane.showConfirmDialog(this,
                                        "Esta seguro de eliminar la venta ?",
                                        "Eliminar",
                                        JOptionPane.YES_NO_OPTION);

            // Si no desea borrarlo, entonces no lo borra
            if(rta == JOptionPane.NO_OPTION) {
                txtCodigo.requestFocus();
                return;
            }
            try {
                conn = AdministradorDeConexiones.obtenerConexion();
                /*Le pedimos a la listaVentas el item que vamos a borrar*/
                Venta venta = (Venta) listaVentas.get(tablaVentas.getSelectedRow());
                //Eliminamos el item de la mesa, se borra de la base de datos
                VentasDao.getInstance().eliminarItem(conn, venta.getId());
                vaciarModeloVentas();
                cargarVenta();
                totalizar();
            }
            catch(Exception e) {e.printStackTrace();}
        }
    }//GEN-LAST:event_btnEliminarActionPerformed

    private void btnConfirmarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnConfirmarActionPerformed
        // TODO add your handling code here:
        Connection conn = null;
        if (tablaVentas.getRowCount() == 0) {
            JOptionPane.showMessageDialog(this, "No existen ventas a Confirmar!!!", "Error", JOptionPane.INFORMATION_MESSAGE);
            txtCodigo.requestFocus();
        }
        else {
            int rta = JOptionPane.showConfirmDialog(this,
                                        "Confirma la Venta ?",
                                        "Cargar Venta",
                                        JOptionPane.YES_NO_OPTION);

            // Si no desea confirmar la venta, entonces no la confirma
            if(rta == JOptionPane.NO_OPTION) {
                txtCodigo.requestFocus();
                return;
            }
            try {
                conn = AdministradorDeConexiones.obtenerConexion();
                VentasDao.getInstance().efectuarVenta(conn);
                vaciarModeloVentas();
                cargarVenta();
                totalizar();
                txtCodigo.requestFocus();
            }
            catch(Exception e) {e.printStackTrace();}
        }
    }//GEN-LAST:event_btnConfirmarActionPerformed

    
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btnConfirmar;
    private javax.swing.JButton btnEliminar;
    private javax.swing.JButton btnSalir;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel9;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JPanel jPanel2;
    private javax.swing.JPanel jPanel3;
    private javax.swing.JPanel jPanel4;
    private javax.swing.JPanel jPanel5;
    private javax.swing.JPanel jPanel6;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JSeparator jSeparator1;
    private javax.swing.JSeparator jSeparator2;
    private javax.swing.JLabel lblApertura;
    private javax.swing.JLabel lblCantidad;
    private javax.swing.JLabel lblCodigo;
    private javax.swing.JLabel lblFecha;
    private javax.swing.JLabel lblFecha1;
    private javax.swing.JLabel lblHora;
    private javax.swing.JLabel lblTotal;
    private javax.swing.JLabel lblUsr;
    private javax.swing.JLabel lblUsuario;
    private javax.swing.JTable tablaVentas;
    private javax.swing.JTextField txtCantidad;
    private javax.swing.JTextField txtCodigo;
    // End of variables declaration//GEN-END:variables

    private void estructurarTabla() {
        tablaVentas.getColumnModel().getColumn(0).setPreferredWidth(10);
        tablaVentas.getColumnModel().getColumn(1).setPreferredWidth(350);
        tablaVentas.getColumnModel().getColumn(2).setPreferredWidth(10);
        tablaVentas.getColumnModel().getColumn(3).setPreferredWidth(10);
    }


    //Devuelve la hora actual del sistema
    private String devolverHoraActual() {
        SimpleDateFormat hms;
        hms = new SimpleDateFormat("HH:mm:ss");
        return (new String(hms.format(hoy)));
    }

    //Devuelve la fecha actual del sistema
    private String devolverFechaActual() {
        Calendar actual = Calendar.getInstance();
        SimpleDateFormat sdf=new SimpleDateFormat("dd/MM/yyyy");
        return(sdf.format(hoy));
    }

    private void cargarVenta() {
        Connection conn = null;
        listaVentas = null;

        /*
         * tuplaVentas es un vector utilizado para cargar los datos necasarios a representar en la grilla de
         * ventas y luego agregarselo al modeloVentas
         */
        String[] tuplaVentas = null;

        try {
            conn = AdministradorDeConexiones.obtenerConexion();
            //listaMesa se utiliza para almacenar los ArrayLists devueltos por la consulta de la base
            listaVentas = VentasDao.getInstance().getTodos(conn);
            Iterator iteraListaVenta = listaVentas.iterator();
            vaciarModeloVentas();
        
            /*
            Lista utilizada como un espejo del modeloMesas(contiene los registros completos de la tabla mesa)
            para poder contener los id de la tabla mesas y cuando se realiza un eliminacion o una modificacion
            poder localizarlo en la tabla mesas
            */

            while (iteraListaVenta.hasNext()) {
                 //Obtenemos la mesa devuelta por lista
                Venta venta = (Venta) iteraListaVenta.next();
                /*Ahora vamos a crear el vector que representa la tupla para asignarlo en la grilla*/
                tuplaVentas = new String[4];
                /*Seteamos la columna cantidad*/
                tuplaVentas[0] = String.valueOf(venta.getCantidad());
                /*Seteamos la columna descripcion*/
                tuplaVentas[1] = venta.getArt().getDescrip();

                /*Seteamos la columna de precio unitario*/
                //tuplaVentas[2] = String.format("%.2f",venta.getArt().getPreVenta());

                tuplaVentas[2] = String.valueOf(venta.getArt().getPreVenta());
                tuplaVentas[3] = String.valueOf(venta.getTotal());
            

                //Agrego la fila en el modelo de mesas para que se vea reflejado en la grilla
                modeloVentas.addRow(tuplaVentas);
            }
        }catch(Exception e) {e.printStackTrace();}
    }

    
    private void totalizar() {
        float total = 0;
        for (int i=0; i < modeloVentas.getRowCount(); i++) {
            total+=Float.parseFloat((String) modeloVentas.getValueAt(i, 3));
        }
        //lblTotal.setText(String.valueOf(total));
        lblTotal.setText(String.format("%.2f",total));
        txtCodigo.requestFocus();
    }


    private void vaciarModeloVentas() {
        modeloVentas.setRowCount(0);
    }

    private void vaciarTablaVentas() {
        Connection conn = null;
        try {
            conn = AdministradorDeConexiones.obtenerConexion();
            VentasDao.getInstance().vaciarTablaVentas(conn);
        }catch(Exception e) {e.printStackTrace();}
    }

    private float obtenerPrecioDeCodigoDeBarra(String codBarra) {
        float precio = 0;
        try {
            String parteDecimal = codBarra.substring(6, 10);
            /**
             * al string de la parte decimal le concateno el punto para poder interpretarlo como float
             */
            precio = Float.parseFloat(parteDecimal.concat(".").concat(codBarra.substring(10, 12)));
        }catch(NumberFormatException nfe){
            nfe.printStackTrace();
        }
        return precio;
    }

}
